from typing import List, Optional, Dict, Any
from fastapi import APIRouter, Depends, HTTPException, Query, Body
from motor.motor_asyncio import AsyncIOMotorDatabase
from bson import ObjectId
from datetime import datetime

from app.api.deps import get_current_user, get_database
from app.models.state import (
    StateCreate, StateUpdate, StateResponse, 
    ModuleStateResponse, ModuleType
)
from app.models.user import User
from app.core.response import success_response, error_response, ErrorTypes, ErrorMessages, ApiResponse
from app.services.state_service import StateService
import logging

logger = logging.getLogger(__name__)

router = APIRouter()


@router.get("/", response_model=ApiResponse, summary="获取状态列表")
async def list_states(
    module_type: Optional[ModuleType] = Query(None, description="模块类型筛选"),
    is_enabled: Optional[bool] = Query(None, description="启用状态筛选"),
    is_visible: Optional[bool] = Query(None, description="可见性筛选"),
    search: Optional[str] = Query(None, description="搜索关键词"),
    skip: int = Query(0, ge=0, description="跳过数量"),
    limit: int = Query(100, ge=1, le=1000, description="限制数量"),
    db: AsyncIOMotorDatabase = Depends(get_database),
    current_user: User = Depends(get_current_user)
):
    """获取状态列表"""
    try:
        # 使用服务层获取状态列表
        result = await StateService.get_states(
            db=db,
            module_type=module_type,
            is_enabled=is_enabled,
            is_visible=is_visible,
            search=search,
            skip=skip,
            limit=limit
        )
        
        return success_response(
            data=result,
            message="获取状态列表成功"
        )
        
    except Exception as e:
        return error_response(
            error_type=ErrorTypes.QUERY_ERROR,
            message=f"获取状态列表失败: {str(e)}"
        )


@router.get("/{state_id}", response_model=ApiResponse, summary="获取状态详情")
async def get_state(
    state_id: str,
    db: AsyncIOMotorDatabase = Depends(get_database),
    current_user: User = Depends(get_current_user)
):
    """获取状态详情"""
    try:
        # 使用服务层获取状态详情
        state_response = await StateService.get_state(db, state_id)
        
        if not state_response:
            return error_response(
                error_type=ErrorTypes.NOT_FOUND_ERROR,
                message="状态不存在"
            )
        
        return success_response(
            data=state_response,
            message="获取状态详情成功"
        )
        
    except Exception as e:
        return error_response(
            error_type=ErrorTypes.QUERY_ERROR,
            message=f"获取状态详情失败: {str(e)}"
        )


@router.post("/", response_model=ApiResponse, summary="创建状态")
async def create_state(
    state_data: StateCreate,
    db: AsyncIOMotorDatabase = Depends(get_database),
    current_user: User = Depends(get_current_user)
):
    """创建状态"""
    try:
        # 使用服务层创建状态
        state_response = await StateService.create_state(db, state_data)
        
        return success_response(
            data=state_response,
            message="状态创建成功"
        )
    except ValueError as e:
        return error_response(
            error_type=ErrorTypes.CONFLICT_ERROR,
            message=str(e),
            field="code"
        )
    except Exception as e:
        return error_response(
            error_type=ErrorTypes.INTERNAL_ERROR,
            message=f"创建状态失败: {str(e)}"
        )


@router.put("/{state_id}", response_model=ApiResponse, summary="更新状态")
async def update_state(
    state_id: str,
    state_data: StateUpdate,
    db: AsyncIOMotorDatabase = Depends(get_database),
    current_user: User = Depends(get_current_user)
):
    """更新状态"""
    try:
        # 使用服务层更新状态
        state_response = await StateService.update_state(db, state_id, state_data)
        
        if not state_response:
            return error_response(
                error_type=ErrorTypes.NOT_FOUND_ERROR,
                message="状态不存在或更新失败"
            )
        
        return success_response(
            data=state_response,
            message="状态更新成功"
        )
    except ValueError as e:
        if "不存在" in str(e):
            return error_response(
                error_type=ErrorTypes.NOT_FOUND_ERROR,
                message=str(e)
            )
        elif "已存在" in str(e):
            return error_response(
                error_type=ErrorTypes.CONFLICT_ERROR,
                message=str(e),
                field="code"
            )
        return error_response(
            error_type=ErrorTypes.VALIDATION_ERROR,
            message=str(e)
        )
    except Exception as e:
        return error_response(
            error_type=ErrorTypes.INTERNAL_ERROR,
            message=f"更新状态失败: {str(e)}"
        )


@router.patch("/batch-sort", response_model=ApiResponse, summary="批量更新状态排序")
async def batch_update_sort_order(
    updates: List[Dict[str, Any]],
    db: AsyncIOMotorDatabase = Depends(get_database),
    current_user: User = Depends(get_current_user)
):
    """批量更新状态排序顺序
    
    updates格式: [{"id": "state_id", "sort_order": 1}, ...]
    """
    try:
        from bson import ObjectId
        
        updated_count = 0
        now = datetime.utcnow()
        
        for update_item in updates:
            state_id = update_item.get("id")
            sort_order = update_item.get("sort_order")
            
            if not state_id or sort_order is None:
                continue
            
            try:
                object_id = ObjectId(state_id)
            except Exception:
                continue
            
            result = await db.states.update_one(
                {"_id": object_id},
                {
                    "$set": {
                        "sort_order": sort_order,
                        "updated_at": now
                    }
                }
            )
            
            if result.modified_count > 0:
                updated_count += 1
        
        # 清除所有相关缓存（传入None表示清除所有）
        from app.services.state_service import state_cache
        state_cache.invalidate_cache(None)
        
        return success_response(
            data={"updated_count": updated_count},
            message=f"成功更新 {updated_count} 个状态的排序"
        )
    except Exception as e:
        logger.error(f"批量更新排序失败: {str(e)}")
        return error_response(
            error_type=ErrorTypes.INTERNAL_ERROR,
            message=f"批量更新排序失败: {str(e)}"
        )


@router.delete("/batch", response_model=ApiResponse, summary="批量删除状态")
async def batch_delete_states(
    body: dict = Body(...),
    db: AsyncIOMotorDatabase = Depends(get_database),
    current_user: User = Depends(get_current_user)
):
    """批量删除状态"""
    try:
        # 从请求体中获取状态ID列表
        state_ids = body.get("state_ids", [])
        
        # 处理不同的输入格式
        if isinstance(state_ids, str):
            state_ids = [state_ids.strip()]
        elif isinstance(state_ids, (set, tuple)):
            state_ids = [str(i).strip() for i in state_ids]
        elif not isinstance(state_ids, list):
            return error_response(
                error_type=ErrorTypes.VALIDATION_ERROR,
                message="状态ID列表格式错误，期望数组格式"
            )
        else:
            # 过滤空值和None，转换为字符串
            state_ids = [str(i).strip() for i in state_ids if i is not None and str(i).strip()]
        
        if not state_ids:
            return error_response(
                error_type=ErrorTypes.VALIDATION_ERROR,
                message="状态ID列表不能为空"
            )
        
        # 从请求体中获取force参数
        force = body.get("force", False)
        
        # 使用服务层批量删除状态
        result = await StateService.batch_delete_states(db, state_ids, force=force)
        
        # 构建返回消息
        message_parts = []
        if result.get("deleted_count", 0) > 0:
            message_parts.append(f"成功删除 {result['deleted_count']} 个状态")
        if result.get("skipped_count", 0) > 0:
            message_parts.append(f"跳过 {result['skipped_count']} 个状态")
        
        message = "，".join(message_parts) if message_parts else "没有状态被删除"
        
        # 如果有错误，在消息中附加提示
        if result.get("errors") and len(result["errors"]) > 0:
            # 显示前3个错误
            error_preview = result["errors"][:3]
            if len(result["errors"]) > 3:
                message += f"，共 {len(result['errors'])} 个错误，详情请查看errors字段"
            else:
                message += "，详情请查看errors字段"
        
        return success_response(
            data=result,
            message=message
        )
        
    except ValueError as e:
        return error_response(
            error_type=ErrorTypes.VALIDATION_ERROR,
            message=str(e)
        )
    except Exception as e:
        logger.error(f"批量删除状态失败: {str(e)}", exc_info=True)
        return error_response(
            error_type=ErrorTypes.INTERNAL_ERROR,
            message=f"批量删除状态失败: {str(e)}"
        )


@router.delete("/{state_id}", response_model=ApiResponse, summary="删除状态")
async def delete_state(
    state_id: str,
    force: bool = Query(False, description="是否强制删除（即使有数据也删除）"),
    db: AsyncIOMotorDatabase = Depends(get_database),
    current_user: User = Depends(get_current_user)
):
    """删除状态"""
    try:
        # 使用服务层删除状态（force参数不再使用，总是允许删除）
        result = await StateService.delete_state(db, state_id, force=False)
        
        # 删除成功，如果有警告信息也一并返回
        message_text = result.get("message", "状态删除成功")
        if result.get("warning"):
            message_text = f"{message_text}（{result.get('warning')}）"
        
        return success_response(
            data={
                "deleted_id": state_id,
                "warning": result.get("warning"),
                "has_data": result.get("has_data", False),
                "data_count": result.get("data_count", 0),
                "module_name": result.get("module_name", ""),
                "state_name": result.get("state_name", "")
            },
            message=message_text
        )
    except ValueError as e:
        if "不存在" in str(e):
            return error_response(
                error_type=ErrorTypes.NOT_FOUND_ERROR,
                message=str(e)
            )
        return error_response(
            error_type=ErrorTypes.VALIDATION_ERROR,
            message=str(e)
        )
    except Exception as e:
        logger.error(f"删除状态失败: {str(e)}", exc_info=True)
        return error_response(
            error_type=ErrorTypes.INTERNAL_ERROR,
            message=f"删除状态失败: {str(e)}"
        )


@router.get("/module/{module_type}", response_model=ApiResponse[List[StateResponse]], summary="获取模块状态")
async def get_module_states(
    module_type: str,
    include_disabled: bool = Query(False, description="是否包含已禁用的状态"),
    db: AsyncIOMotorDatabase = Depends(get_database),
    current_user: User = Depends(get_current_user)
):
    """获取指定模块的所有状态"""
    try:
        # 使用服务层获取模块状态
        state_responses = await StateService.get_module_states(db, module_type, include_disabled)
        
        return success_response(
            data=state_responses,
            message=f"获取{module_type}模块状态成功"
        )
        
    except Exception as e:
        return error_response(
            error_type=ErrorTypes.QUERY_ERROR,
            message=f"获取模块状态失败: {str(e)}"
        )


@router.post("/module/{module_type}/init", response_model=ApiResponse, summary="初始化模块状态")
async def init_module_states(
    module_type: str,
    db: AsyncIOMotorDatabase = Depends(get_database),
    current_user: User = Depends(get_current_user)
):
    """初始化模块状态（支持重复初始化，自动识别硬编码初始值的变化）"""
    try:
        # 使用服务层初始化模块状态
        result = await StateService.init_module_states(db, module_type)
        
        # 构建返回消息
        message_parts = []
        if result["created_count"] > 0:
            message_parts.append(f"创建{result['created_count']}个状态")
        if result["updated_count"] > 0:
            message_parts.append(f"更新{result['updated_count']}个状态")
        if result["disabled_count"] > 0:
            message_parts.append(f"禁用{result['disabled_count']}个不在默认列表中的状态")
        
        if not message_parts:
            message = f"{module_type}模块状态已是最新，无需更新"
        else:
            message = f"{module_type}模块状态同步成功，" + "，".join(message_parts)
        
        return success_response(
            data=result,
            message=message
        )
        
    except ValueError as e:
        return error_response(
            error_type=ErrorTypes.VALIDATION_ERROR,
            message=str(e)
        )
    except Exception as e:
        return error_response(
            error_type=ErrorTypes.INTERNAL_ERROR,
            message=f"初始化模块状态失败: {str(e)}"
        )


@router.get("/module/{module_type}/options", response_model=ApiResponse, summary="获取模块状态选项")
async def get_module_state_options(
    module_type: str,
    db: AsyncIOMotorDatabase = Depends(get_database),
    current_user: User = Depends(get_current_user)
):
    """获取模块状态选项（用于前端下拉框）"""
    try:
        # 使用服务层获取模块状态选项
        options = await StateService.get_module_state_options(db, module_type)
        
        return success_response(
            data=options,
            message=f"获取{module_type}模块状态选项成功"
        )
        
    except Exception as e:
        return error_response(
            error_type=ErrorTypes.QUERY_ERROR,
            message=f"获取模块状态选项失败: {str(e)}"
        )


@router.get("/module/{module_type}/validate/{code}", response_model=ApiResponse, summary="验证状态代码")
async def validate_state_code(
    module_type: str,
    code: str,
    db: AsyncIOMotorDatabase = Depends(get_database),
    current_user: User = Depends(get_current_user)
):
    """验证状态代码是否有效"""
    try:
        # 使用服务层验证状态代码
        is_valid = await StateService.validate_state_code(db, module_type, code)
        
        return success_response(
            data={"is_valid": is_valid},
            message="状态代码验证完成"
        )
        
    except Exception as e:
        return error_response(
            error_type=ErrorTypes.QUERY_ERROR,
            message=f"状态代码验证失败: {str(e)}"
        )


@router.get("/module/{module_type}/default", response_model=ApiResponse, summary="获取模块默认状态")
async def get_default_state(
    module_type: str,
    db: AsyncIOMotorDatabase = Depends(get_database),
    current_user: User = Depends(get_current_user)
):
    """获取模块默认状态"""
    try:
        # 使用服务层获取默认状态
        default_state = await StateService.get_default_state(db, module_type)
        
        if not default_state:
            return error_response(
                error_type=ErrorTypes.NOT_FOUND_ERROR,
                message=f"{module_type}模块没有默认状态"
            )
        
        return success_response(
            data=default_state,
            message=f"获取{module_type}模块默认状态成功"
        )
        
    except Exception as e:
        return error_response(
            error_type=ErrorTypes.QUERY_ERROR,
            message=f"获取默认状态失败: {str(e)}"
        )


@router.get("/types/generate", response_model=ApiResponse, summary="生成TypeScript类型定义")
async def generate_typescript_types(
    db: AsyncIOMotorDatabase = Depends(get_database),
    current_user: User = Depends(get_current_user)
):
    """生成TypeScript类型定义"""
    try:
        # 使用服务层生成TypeScript类型
        types_content = await StateService.generate_typescript_types(db)
        
        return success_response(
            data={"content": types_content},
            message="TypeScript类型定义生成成功"
        )
        
    except Exception as e:
        return error_response(
            error_type=ErrorTypes.INTERNAL_ERROR,
            message=f"生成TypeScript类型定义失败: {str(e)}"
        )


@router.post("/cache/invalidate", response_model=ApiResponse, summary="清除状态缓存")
async def invalidate_cache(
    module_type: Optional[str] = None,
    current_user: User = Depends(get_current_user)
):
    """清除状态缓存"""
    try:
        # 使用服务层清除缓存
        await StateService.invalidate_cache(module_type)
        
        message = f"清除{module_type}模块缓存成功" if module_type else "清除所有状态缓存成功"
        return success_response(
            data={"invalidated": True},
            message=message
        )
        
    except Exception as e:
        return error_response(
            error_type=ErrorTypes.INTERNAL_ERROR,
            message=f"清除缓存失败: {str(e)}"
        )